package com.blog.controller;

import com.blog.entity.Comment;
import com.blog.service.BlogService;
import com.blog.service.CommentService;
import com.blog.vo.DetailedBlog;
import com.blog.vo.FirstPageBlog;
import com.blog.vo.RecommendBlog;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * 首页控制器
 */
@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private CommentService commentService;

    //    分页查询博客列表
    @GetMapping("/")
    public String index(Model model, @RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        PageHelper.startPage(pageNum,8);
        List<FirstPageBlog> allFirstPageBlog = blogService.getAllFirstPageBlog();       //博文列表

        List<RecommendBlog> recommendedBlog = blogService.getRecommendedBlog();         //推荐文章

//        PageInfo<FirstPageBlog> pageInfo = new PageInfo<>(allFirstPageBlog);
        model.addAttribute("pageInfo",allFirstPageBlog);
        model.addAttribute("recommendedBlogs", recommendedBlog);

//        System.out.println(allFirstPageBlog);
//        System.out.println(recommendedBlog);

        return "index";
    }

    //    搜索博客
    @PostMapping("/search")
    public String search(Model model,
                         @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum,
                         @RequestParam String query) {

//        System.out.println("------------------query:" + query);

        PageHelper.startPage(pageNum, 1000);
        List<FirstPageBlog> searchBlog = blogService.getSearchBlog(query);
//        PageInfo<FirstPageBlog> pageInfo = new PageInfo<>(searchBlog);
        model.addAttribute("pageInfo", searchBlog);
        model.addAttribute("query", query);

//        System.out.println("++++++++++++++++++搜索博客:" + searchBlog);

        return "search";
    }

    //    跳转博客详情页面
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model) {
        DetailedBlog detailedBlog = blogService.getDetailedBlog(id);
        List<Comment> comments = commentService.listCommentByBlogId(id);
        model.addAttribute("comments", comments);

//        System.out.println("=============="+detailedBlog);

        model.addAttribute("blog", detailedBlog);
        return "blog";
    }

}
